<template>
  <div class="home" :style="computeStyle">
    <msg v-show="$store.state.msg_show" />
    <superman v-show="$store.state.superman_show" />
    <guizeBox ref="gbb" v-show="$store.state.gz_show" />
    <loading v-show="this.isloading" />
    <div class="home2">
      <div class="column">
        <img src="../../assets/img/biaoti.png">
      </div>
    </div>
    <div class="planting">
      <div class="column">
        <img @click="toGuize()" src="../../assets/img/guize.png">
      </div>
      <div class="column2" :style="mb">
        <div class="col1">
            <!-- 初始化 -->
            <div class="one"  v-show="this.pageState==1">
                <div class="zhuligaokao" @click="toCount('go500')" ></div>
            </div>
            <!-- 奖品已领取完 -->
            <div class="one"  v-show="this.pageState==5">
                <div class="guangle" ></div>
            </div>
            <!-- 我以获得 -->
            <div class="three"  v-show="this.pageState==2">
              <div class="t1">
                <div class="x500m"></div>
              </div>
              <div class="t2">
                <div class="gaosupengyou" @click="toCount('tell')"></div>
              </div>
            </div>
            <!-- 可助力 -->
            <div class="three"  v-show="this.pageState==3">
              <div class="t1">
                <div :class="iszl" @click="toCount('zhuli')"></div>
              </div>
              <div class="t2">
                <div class="woyao" @click="toCount('woyao')"></div>
              </div>
            </div>
            <!-- 好友以获得 -->
            <div class="three"  v-show="this.pageState==4">
              <div class="t1">
                <div class="haoyouhuode"></div>
              </div>
              <div class="t2">
                <div class="woyao" @click="toCount('woyao')"></div>
              </div>
            </div>
        </div>
        <div class="col2">
          <div class="cb2">
            <div class="yuyue" @click="toCount('yuyue')"/>
          </div>
          <div class="cb" :style="cbs">
              <img class="banli"  @click="toCount('banli')" :style="banlis" src="../../assets/img/banli.png"/>
              <img class="qiandao" @click="toCount('qiandao')" :style="qiandaos" src="../../assets/img/qiandao.png"/>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import '../../assets/css/index.less'
import { mapMutations, mapGetters, mapActions } from 'vuex'
import { addData, getData, getSessionData, addSessionData, removeSessionData } from '@/util/localData'
import base from '../../constant/base'
import superman from './superman.vue'
import msg from './msg.vue'
import loading from './loading.vue'
import guizeBox from './guize-box.vue'
import axios from 'axios'
import wx from 'weixin-js-sdk'

export default {
  name: 'home',
  components:{
    guizeBox,
    superman,
    msg,
    loading
  },
  computed: {
    computeStyle() {
      return { backgroundSize: this.clientHeight/this.clientWidth > 1.65 ? "100% auto" : "100% 100%" }
    },
    iszl() {
      return this.isZhuLi?"yizhuli":"bangta"
    },
    mb(){
      return { marginBottom: this.clientHeight/this.clientWidth > 1.65 ? (this.clientHeight - 1160*this.clientWidth/750)+"px" : "5%"}
    },
    cbs(){
      return { wdith: this.clientWidth <= 320 ? "45%":"40%"}
    },
    banlis(){
      return { wdith:this.clientWidth<320 ? "53.6px" : "67px",height:this.clientWidth<320 ? "36px":"45px"}
    },
    qiandaos(){
      return { wdith: this.clientWidth<320 ?"51.6px":"64.5px",height: this.clientWidth<320 ? "32.6px":"42px"}
    }
  },
  data () {
    return {
      clientHeight: document.documentElement.clientHeight,
      clientWidth: document.documentElement.clientWidth,
      pageState: 0, //用户状态 0：不显示按钮，1：显示500 2：显示已领取 3：显示帮助力 4：显示好友以助力 5:已助力但是奖品为0
      isZhuLi: false, //用户是否已经点击帮助力
      isloading: true //是不是等待
    }
  },
  mounted() {
    this.clientHeight = document.documentElement.clientHeight;
    this.clientWidth = document.documentElement.clientWidth;
  },
  updated(){
    console.log("更新")
    this.$refs.gbb.toUpdate()
  },
  created() {
    this.setFen()
    let zId = this.$route.query.zuID
    if(zId){//通过别人分享进入,保存zId到session
      addSessionData("zhuli_openId",zId)
    }
    console.log(this.$route.query)
    let status = this.$route.query.status
    if(!status){//未获取openID
      window.location.href = base.url+"wx/getCode" //获取用户信息
      //window.location.href = "http://localhost:12401/getCode" //测试重定向
      setTimeout(()=>{
        location.reload()
      },6000)
    }else{
      this.isloading = false
      let userInfo = {
        openid:this.$route.query.openId,
        status:this.$route.query.status,
        telNum:this.$route.query.telNum,
        provinceCode:this.$route.query.provinceCode, //省份
        cityCode:this.$route.query.cityCode, //城市
      }
      console.log("url中获取的用户信息")
      console.log(userInfo)
      addSessionData("zhili_userInfo",userInfo)
      
      console.log("助力Id："+getSessionData("zhuli_openId")+"=====助力openid："+userInfo.openid);
      if(getSessionData("zhuli_openId")==userInfo.openid)console.log("当前用户打开自己分享的链接")

      if(getSessionData("zhuli_openId") &&
        getSessionData("zhuli_openId")!=userInfo.openid){//打开分享页面 & 不是打开自己分享的页面
        //查询是否获得 （通过zid）
        axios.post(base.url+"user/help/selUser", {openId:getSessionData("zhuli_openId")}).then((res)=>{
          console.log(res)
          if(res.data.code=="SUCCESS"){
            let userHelp = res.data.data;
            if(userHelp.openIdHelp){//您的好友以获得500
              if(userHelp.prize){
                this.pageState = 4
              }else{
                this.pageState = 3
                this.isZhuLi = true
              }
            }else{//帮他助力
              this.pageState = 3
            }
          }else{
            this.$store.state.msg_title = "很抱歉~"
            this.$store.state.msg_content = res.data.msg
            this.showMsg()
          }
        })
      }else{//自己打开页面（无分享人）
        //查询是否获得 （通过session的openid查询）
        axios.post(base.url+"user/help/selUser", {openId:userInfo.openid}).then((res)=>{
          console.log(res)
          if(res.data.code=="SUCCESS"){
            let userHelp = res.data.data;
            if(userHelp==null || !userHelp.openIdHelp){//显示助力免费得流量
              this.pageState = 1
            }else if(userHelp.openIdHelp && userHelp.prize){//显示以获得500
              this.pageState = 2
            }else if(userHelp.openIdHelp && !userHelp.prize){//奖品发放结束
              this.pageState = 5
            }
          }else{
            this.$store.state.msg_title = "很抱歉~"
            this.$store.state.msg_content = res.data.msg
            this.showMsg()
          }
        })
      }

      //记录用户进入
      this.toCount("init",userInfo)
    }
  },
  methods: {
        ...mapActions({                    //映射Mutations
            selRule: 'SEL_RULE',
        }),
        ...mapMutations({                 //引入 修改状态的方法  就可以用 this.setSinger()     //来进行修改状态(状态改变会自动渲染你所关联的组件)         
            showMsg: 'SHOW_MSG',
            showSuperMan: 'SHOW_SUPER_MAN',
        }),
        toGuize:function(){
          this.selRule()
        },
        validateUser:function(user,myRollback,prame){
          axios.get(base.url+"rule/selOverdue", {}).then((res)=>{
            let rs = res.data;
            console.log(rs)
              //判断活动过期
              if(rs.code=="SUCCESS"){
                //判断用户是否关注  和  是否指定省份用户  和  手机绑定状态
                if(user.status=="3001"){
                  // this.$store.state.msg_u = "/code"
                  // this.$store.state.msg_title = "很抱歉~"
                  // this.$store.state.msg_content = "您未关注公众号"
                  // this.showMsg()
                  this.$router.push("/code")
                  return false
                }else if(user.provinceCode!="431"){
                  // this.$store.state.msg_u = "/code"
                  // this.$store.state.msg_title = "很抱歉~"
                  // this.$store.state.msg_content = "您非省内用户"
                  //this.showMsg()
                  this.$router.push("/code")
                  return false
                }else if(!user.telNum){
                  // this.$store.state.msg_u = "/login"
                  // this.$store.state.msg_title = "很抱歉~"
                  // this.$store.state.msg_content = "您未绑定手机号"
                  // this.showMsg()
                  this.$router.push("/login")
                  return false
                }else{
                  if(myRollback){
                    if(prame){
                      myRollback(user,prame)
                    }else{
                      myRollback(user)
                    }
                  }
                }
              }else{
                this.showMsg()
                this.$store.state.msg_title = "很抱歉~"
                this.$store.state.msg_content = rs.msg
                return false
              }
          })
        },
        setFen:function(){
          axios.get(base.url+"wx/getJSAPI", {}).then((res)=>{
            if(res.data.status!=0){
              alert("jsapi_ticket获取失败")
            }else{
              wx.config({
              debug: false, 
              appId: base.appId, // 必填，公众号的唯一标识
              timestamp: res.data.timeStamp, // 必填，生成签名的时间戳
              nonceStr: res.data.nonceStr, // 必填，生成签名的随机串
              signature: res.data.jsSignature,
              jsApiList: ['onMenuShareTimeline','hideMenuItems']
              })
              wx.ready(function() {//通过ready接口处理成功验证
                wx.hideMenuItems({
                  menuList: ['menuItem:share:appMessage'], // 要隐藏的菜单项，只能隐藏“传播类”和“保护类”按钮
                  success:function(res){
                    console.log("隐藏成功")
                    console.log(res)
                  },
                  fail:function(res){
                    console.log("隐藏失败")
                    console.log(JSON.stringify(res))
                  }
                })
                let linkUrl = base.forendUrl
                wx.onMenuShareTimeline({ //分享朋友圈
                  title: '助力高考，免费领500M流量', // 分享标题
                  link: linkUrl,
                  imgUrl: base.url+'img/mlogo.jpg', // 分享图标
                })

              })
            }
          })
        },
        fenxiang:function(user,type){
          axios.get(base.url+"wx/getJSAPI", {}).then((res)=>{
            console.log(res.data.status)
            if(res.data.status!=0){
              alert("jsapi_ticket获取失败")
            }else{
              wx.config({
              debug: false, 
              appId: base.appId, // 必填，公众号的唯一标识
              timestamp: res.data.timeStamp, // 必填，生成签名的时间戳
              nonceStr: res.data.nonceStr, // 必填，生成签名的随机串
              signature: res.data.jsSignature,
              //jsApiList: ['onMenuShareAppMessage','onMenuShareTimeline']
              jsApiList: ['onMenuShareTimeline','hideMenuItems']
              })
              wx.ready(function() {//通过ready接口处理成功验证
                wx.hideMenuItems({
                  menuList: ['menuItem:share:appMessage'], // 要隐藏的菜单项，只能隐藏“传播类”和“保护类”按钮
                  success:function(res){
                    console.log("隐藏成功")
                    console.log(res)
                  },
                  fail:function(res){
                    console.log("隐藏失败")
                    console.log(JSON.stringify(res))
                  }
                })
                let prame = encodeURIComponent(user.openid)
                let linkUrl = base.url+'wx/fenxiang?zuID='+prame
                if(type=="noZid"){
                  linkUrl = base.forendUrl
                }
                // wx.onMenuShareAppMessage({
                //   title: '助力高考，免费领500M流量', // 分享标题
                //   desc: '一共10万份，手快有，手慢无！', // 分享描述
                //   link: linkUrl,
                //   imgUrl: base.url+'img/mlogo.png',
                //   success: function () {
                //     axios.post(base.url+"user/help/userInit", {openId:user.openid,telnum:user.telNum}).then((res)=>{
                //       console.log("用户初始化===》"+res.data.code)
                //     })
                //   },
                // })
                wx.onMenuShareTimeline({ //分享朋友圈
                  title: '助力高考，免费领500M流量', // 分享标题
                  link: linkUrl,
                  imgUrl: base.url+'img/mlogo.jpg', // 分享图标
                  success: function () {
                    axios.post(base.url+"user/help/userInit", {openId:user.openid,telnum:user.telNum}).then((res)=>{
                      console.log("用户初始化===》"+res.data.code)
                    })
                  },
                })

              })
            }
          })
          this.showSuperMan()
        },
        toHelpUser:function(user){
          axios.post(base.url+"user/help/addUserPrize", {openId:getSessionData("zhuli_openId"),openIdHelp:user.openid,telnumHelp:user.telNum}).then((res)=>{
              console.log(res)
              if(res.data.code=="SUCCESS"){
                this.$store.state.msg_title = "恭喜您!"
                if(res.data.data){
                  this.$store.state.msg_content = "助力成功，好友已经获得500M流量"
                }else{
                  this.$store.state.msg_content = "助力成功"
                }
                this.showMsg()
                this.isZhuLi = true
              }else{
                this.$store.state.msg_title = "很抱歉!"
                this.$store.state.msg_content = res.data.msg
                this.showMsg()
              }
          })
        },
        countC:function(type,user){
          console.log(type)
          axios.post(base.url+"record/click", {openId:user.openid,telNum:user.telNum,clickTyep:type})
        },
        toCount:function(type){
          let userInfo = getSessionData("zhili_userInfo")
          let user = JSON.parse(userInfo)
          console.log(user)
          this.countC(type,user)
          if(!user){
            alert("用户信息获取失败")
            return
          }
          // let isOk = this.validateUser(user)
          // if(!isOk){
          //   return
          // }
          //记录点击
          switch (type){
            case "init": //初始化
            this.validateUser(user)
            break;
            case "go500": //黄色 主力高考
            this.validateUser(user,this.fenxiang)
            break;
            case "zhuli": //帮助朋友助力
            //this.toHelpUser(user)
            if(this.pageState==3 && !this.isZhuLi){//显示助力按钮时可用
              this.validateUser(user,this.toHelpUser)
            }
            break;
            case "woyao": //我要流量
            axios.post(base.url+"user/help/selUser", {openId:user.openid}).then((res)=>{
              console.log(res)
              if(res.data.code=="SUCCESS"){
                let userHelp = res.data.data;
                if(!userHelp){
                  console.log("用户为null")
                  this.validateUser(user,this.fenxiang)
                }else{
                  console.log("用户不为null")
                  if(userHelp.prize){//已领奖
                    console.log("已领奖")
                    window.location.href = base.url+"wx/getCode"
                  }else{
                    console.log("未领奖")
                    this.validateUser(user,this.fenxiang)
                  }
                }
              }else{
                this.$store.state.msg_title = "很抱歉~"
                this.$store.state.msg_content = res.data.msg
                this.showMsg()
              }
            })
            break;
            case "tell": //告诉朋友
            this.validateUser(user,this.fenxiang,"noZid")
            break;
            case "banli": //办理有礼
              window.location.href = "http://wx.10086.cn/website/personalHome/new/index?activityId=activityId_newPersonHome_4311528267418439&tid=wechat"
            break;
            case "qiandao": //签到赠流量
              window.location.href = "http://wx.10086.cn/website/personalHome/new/index?activityId=activityId_newPersonHome_4311523424514948&tid=wechat"
            break;
            case "yuyue": //高考预约查询
              window.location.href = "http://wx.10086.cn/website/personalHome/new/index?activityId=activityId_newPersonHome_4311528251271752&tid=wechat"
            break;
            default:
          }
        }
  }
}
</script>
